<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2021/8/10
 * Time: 1:55 下午
 */

namespace app\web\controller;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZhunleGroupRecallRecord;
use app\common\cachemodel\ZhunleGroupUserRecallRecord;
use app\common\cachemodel\ZlCouponAttr;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\Goods;
use app\common\model\User;
use think\Controller;
use think\Env;
use think\Log;

/**
 * Class SensorsGroupRecall
 * @package app\web\controller
 */
class SensorsGroupRecall extends Controller
{
    private $couponTypeName = [
        1 => '折扣',
        2 => '立减',
        3 => '满减',
        4 => '随机',
        5 => '免费',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->assign('oss', Env::get('host.photo'));
        $this->assign('domain', Env::get('host.domain'));
        $headers = $this->request->header();
        $this->assign('app_type', $headers['app-type'] ?? '');
    }

    /**
     * 召回
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $record_id = $this->request->param('record_id');
        //校验token
        $headers = $this->request->header();
        if (isset($headers['app-type']) && in_array($headers['app-type'], ['ios', 'android'], true))
        {
            try
            {
                $auth = new Auth2();
                $uid = (int)$auth->user['id'];
                unset($headers['cookie'], $headers['time'], $headers['content-type'], $headers['content-length']);
            }
            catch (\Exception $e)
            {
                $uid = 0;
            }
        } else
        {
            $uid = 0;
        }
        //获取当前任务优惠券图片
        $record = (new ZhunleGroupRecallRecord())->where('id', $record_id)->field('id,acid,coupon_photos,cids,coupon_expire_time')->find();
        $couponData = (new ZlCouponAttr())->whereIn('id', $record['cids'])->column('name,desc', 'id');
        $couponName = implode(',', array_column($couponData, 'desc'));
        $photoData = [];
        $coupon_photos = $record['coupon_photos'] ? json_decode($record['coupon_photos'], true) : [];
        foreach ($coupon_photos as $k => $photo)
        {
            $temp = explode('|', $photo);
            $photoData[$k] = $temp[0];
        }
        $record['photo'] = $photoData;
        $userRecord = (new ZhunleGroupUserRecallRecord())->where(['uid' => $uid, 'recall_record_id' => $record_id])->field('id,is_receive_coupon')->find();
        if (isset($userRecord['is_receive_coupon']) && $userRecord['is_receive_coupon'])
        {
            $is_receive_coupon = 1;
        } else
        {
            $is_receive_coupon = 0;
        }
        //todo 获取当前用户是否已领取当前任务
        return $this->fetch('sensors_group_recall/message_recall', ['uid' => $uid, 'data' => $record, 'is_receive_coupon' => $is_receive_coupon, 'couponData' => $couponData, 'couponName' => $couponName, 'headers' => json_encode($headers, true), 'version' => Util::androidVersion('2.2.0')]);
    }


    /**
     * 领取优惠券
     */
    public function receiveCoupon()
    {
        $recall_record_id = input('recall_record_id/d', 0);
        $type = input('type/d', 0);//1=>站内 2=>站外
        if ($type === 1)
        {
            //校验token
            $auth = new Auth2();
            $uid = (int)$auth->user['id'];
        } else
        {
            $tel = input('tel', '');
            if (!$tel)
            {
                return show(config('code.error'), '服务异常请稍后重试!');
            }
            //判断手机号是否已注册
            $userInfo = (new User())->where('tel', $tel)->field('id')->find();
            if (!$userInfo)
            {
                return show(config('code.error'), '抱歉该手机号未注册准了账号!');
            }
            $uid = $userInfo['id'];
        }

        $record = (new ZhunleGroupRecallRecord())->where('id', $recall_record_id)->field('is_send_coupon,cids,acid,coupon_expire_time')->find();
        if (!$record)
        {
            return show(config('code.error'), '服务异常请稍后重试!');
        }

        $userRecord = (new ZhunleGroupUserRecallRecord())->where(['uid' => $uid, 'recall_record_id' => $recall_record_id])->field('id,is_receive_coupon')->find();
        if ($userRecord)
        {
            $userCouponModel = new UserCoupon();
            if ($userRecord['is_receive_coupon'] == 0)
            {
                $time = time();
                if ($record['is_send_coupon'] == 1 && $record['cids'])
                {   // 发送优惠券
                    $couponInfos = (new ZlCouponAttr())->field('id,name,desc,type,gids,ur_id')->whereIn('id', $record['cids'])->select();
                    if ($couponInfos)
                    {
                        foreach ($couponInfos as $k => $couponInfoItem)
                        {
                            $cData = [
                                'uid' => $uid,
                                'c_id' => $couponInfoItem['id'],
                                'ur_id' => $couponInfoItem['ur_id'],
                                'start_time' => $time,
                                'end_time' => strtotime("+{$record['coupon_expire_time']} day", $time),
                                'give_time' => $time,
                                'status' => 0,
                                'price' => 0,
                                'is_give' => 0,
                                'create_time' => $time,
                                'update_time' => 0,
                            ];

                            // 写入用户卡券中心
                            $ucId = $userCouponModel->insertGetId($cData);
                            // 更新用户卡券中心缓存
                            $userCouponModel->listDataAdd($uid, [$ucId => $ucId], 1);
                            $couponRangeArr = [];
                            if (!isset($couponInfoItem['couponRangeArr']))
                            {
                                // 神策打点
                                $gidsArr = explode(',', $couponInfoItem['gids']);
                                $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
                            }

                            $sensordData = [
                                'refer_name' => '',
                                'refer_link' => '',
                                'coupon_name' => $couponInfoItem['desc'],
                                'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                                'coupon_type' => $this->couponTypeName[$couponInfoItem['type']],
                                'coupon_range' => $couponRangeArr,
                                'acquire_channel' => "神策分群召回【{$recall_record_id}】",
                                'is_give' => false,
                                'acquire_scene' => '未知',
                            ];
                            if ($type === 1)
                            {
                                $sensordData['acquire_scene'] = 'App内活动H5';
                            } elseif ($type === 2)
                            {
                                $sensordData['acquire_scene'] = 'App外活动H5';
                            }
                            // 神策打点 75 获得优惠券 AcquireCoupon
                            SensorsData::track($uid, true, 'AcquireCoupon', $sensordData);
                        }
                    } else
                    {
                        Log::write('分群召回->优惠券赠送失败：【' . json_encode(['id' => $recall_record_id, 'cids' => $record['cids'], 'coupon_expire_time' => $record['coupon_expire_time'], 'acid' => $record['acid']], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "】uid:{$uid}错误消息：优惠券信息获取失败", 'error', true);
                    }
                    $res = (new ZhunleGroupUserRecallRecord())->updateData($userRecord['id'], ['is_receive_coupon' => 1, 'receive_time' => time()]);
                    if ($res === true)
                    {
                        return show(config('code.success'), '领取成功');
                    }
                    return show(config('code.error'), '领取失败,请稍后重试!');
                }
            } else
            {
                return show(config('code.error'), '你已经参与过此活动!');
            }
        }
        return show(config('code.error'), '你不在此次活动邀请中!');
    }
}
